package cn.kogee.user.service.impl;

import cn.kogee.basic.constants.VerifyCodeConstants;
import cn.kogee.basic.constants.WxConstants;
import cn.kogee.basic.exception.BusinessException;
import cn.kogee.basic.jwt.JwtUtils;
import cn.kogee.basic.jwt.RsaUtils;
import cn.kogee.basic.service.impl.BaseServiceImpl;
import cn.kogee.basic.util.AjaxResult;
import cn.kogee.basic.util.HttpUtil;
import cn.kogee.basic.util.Md5Utils;
import cn.kogee.basic.util.StrUtils;
import cn.kogee.org.dto.LoginDto;
import cn.kogee.system.domain.Menu;
import cn.kogee.system.domain.LoginData;
import cn.kogee.system.mapper.MenuMapper;
import cn.kogee.system.mapper.PermissionMapper;
import cn.kogee.user.domain.Logininfo;
import cn.kogee.user.domain.User;
import cn.kogee.user.domain.Wxuser;
import cn.kogee.user.mapper.LogininfoMapper;
import cn.kogee.user.mapper.UserMapper;
import cn.kogee.user.mapper.WxuserMapper;
import cn.kogee.user.service.ILogininfoService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private MenuMapper menuMapper;
    /**
     * 管理员登录实现
     * @param dto
     * @return
     */
    @Override
    public AjaxResult Loginaccount(LoginDto dto) {
        //账号
        String account = dto.getAccount();
        //密码
        String checkPass = dto.getCheckPass();
        //管理员代值
        Integer type = dto.getType();
        //1.空值校验
        if(StringUtils.isEmpty(account)||StringUtils.isEmpty(checkPass)){
            throw new BusinessException("账号或登录密码不能为空");
        }
        //2.管理员账号校验
        Logininfo logininfo=logininfoMapper.loadByaccount(dto);
        if(logininfo==null){
            throw new BusinessException("该账号不存在");
        }
        //3.密码校验
        String salt = logininfo.getSalt();//获取盐值
        //将盐值和用户输入的密码进行加密
        String Md5Pwd = Md5Utils.encrypByMd5(checkPass + salt);
        if(!Md5Pwd.equals(logininfo.getPassword())){
            throw new BusinessException("密码错误");
        }
        Map<String,Object> map=loginSuccessJwtHandler(logininfo);
        //4.返回信息直接登录
        return AjaxResult.me().setResultObj(map);
    }

    private Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo) {
        try {
            Map<String, Object> map = new HashMap<>();
            //设置登录人信息到要返回给前端的map集合中以及logindata中
            map.put("logininfo",logininfo);
            LoginData loginData = new LoginData();
            loginData.setLogininfo(logininfo);
            //判断是前台员工登录还是后台管理员登录
            if(logininfo.getType()==0){//后台管理员登录
                //查询后台用户权限信息并设置到loginData中
                List<String> permissions = permissionMapper.loadsnBylogininfoID(logininfo.getId());
                map.put("permissions",permissions);
                loginData.setPermissions(permissions);
                //查询后台用户菜单信息并设置到loginData中
                List<Menu> menus=menuMapper.loadMenusBylogininfoId(logininfo.getId());
                map.put("menus",menus);
                loginData.setMenus(menus);
            }
            //将上面三个数据保存到logindata中使用工具类加密
            PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30000);//没有做刷新过期时间
            //最后在将这个数据装到map返回
            map.put("token",jwtToken);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 微信免密登录
     * @param map
     * @return
     */
    @Override
    public AjaxResult weChatLogin(Map<String, String> map) {
        //1.获取前端传递的code
        Object object = map.get("code");
        String code = object.toString();
        //"https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        String url = WxConstants.GET_ACK_URL.replace("APPID", WxConstants.APPID)
                .replace("SECRET", WxConstants.SECRET)
                .replace("CODE", code);
        //使用工具类微信发起请求获取用户信息
        String JSONstr = HttpUtil.httpGet(url);//获得一个json字符串
        JSONObject jsonObject = JSONObject.parseObject(JSONstr);
        //上面对象中获取openID和access_token
        String openId = jsonObject.getString("openid");
        String accessToken = jsonObject.getString("access_token");
        //2.通过微信返回的信息获取其中的openId查询用户信息进而进行判断
       Wxuser wxuser= wxuserMapper.loadByOpenId(openId);
        //3.1如果用户查询出信息则说明证明已经注册进行免密登录
        if (wxuser!=null&&wxuser.getUserId()!=null&&userMapper.loadById(wxuser.getUserId())!=null){//三个限制条件wxuser不能为空,userID不能为空,根据userId查询出的user不能为空
            //进行免密登录
            User user=userMapper.loadById(wxuser.getUserId());
            Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
            Map<String,Object> mapTMp=loginSuccessJwtHandler(logininfo);
            return AjaxResult.me().setSuccess(true).setResultObj(mapTMp);
        }else {
            //3.2如果没有注册则需要返回注册界面要求用户注册
           /* "?accessToken="+accessToken+"&openId="+openId;*/
            String param = "?accessToken=" + accessToken + "&openId=" + openId;
            //其中需要携带openid和access_token返回给前端注册界面
            return AjaxResult.me().setSuccess(false).setResultObj(param);
        }
    }

    /**
     * 微信绑定
     * @param map
     * @return
     */
    @Override
    public AjaxResult loginBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openId = map.get("openId");
        //1.空值校验
        if(StringUtils.isEmpty(phone)||StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("绑定信息不能为空");
        }
        //2.验证码校验
        //2.1从redis中获取验证码
        Object obj = redisTemplate.opsForValue().get(VerifyCodeConstants.WXREGISTER_CODE_PREFIX + phone);
        //2.2校验验证码是否过期
        if(obj==null){
            throw new BusinessException("验证码过期请重新获取");
        }
        //2.3校验验证码是否正确
        String ssmCode = obj.toString().split(":")[0];
        if(!ssmCode.equals(verifyCode)){
            throw new BusinessException("验证码错误，请重新输入");
        }
        //3.发送微信请求获取用户信息
        //3.1将前端传递过来的accessToken和OPENID替换请求中相关参数
        /*"https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";*/
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        //3.2向微信发起请求获取用户信息
        String jsonStr = HttpUtil.httpGet(url);
        //4.处理响应的数据：json字符串 - json对象 - 获取wxUser的信息
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        //4.1将获取的信息绑定到WXuser中
        Wxuser wxuser=jsonStr2Wxuser(jsonObject);
        //5.判断手机号是否已经绑定进行数据落库
        User user = userMapper.loadByPhone(phone);
        if(user==null){//如果查询的用户信息为空则进行绑定
            //根据手机号注册用户信息
            user=User2phone(phone);
            //绑定登录信息
            Logininfo logininfo=logininfo2user(user);
            //保存登录信息
            logininfoMapper.save(logininfo);
            //将登录信息表中的ID绑定给User信息表
            user.setLogininfoId(logininfo.getId());
            //保存用户信息
            userMapper.save(user);
        }
        //保存微信用户信息
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);
        //6.让用户进行免密登录
        //生成token
        String token = UUID.randomUUID().toString();
        //获取用户登录信息
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
        //返回给前端相关信息
        Map<String,Object> TempMap=loginSuccessJwtHandler(logininfo);
        return AjaxResult.me().setSuccess(true).setResultObj(TempMap);
    }

    private Logininfo logininfo2user(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    private User User2phone(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        user.setEmail(null);
        //生成盐值
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        //生成密码
        String password = StrUtils.getComplexRandomString(8);
        //盐值加密
        String MD5Pwd = Md5Utils.encrypByMd5(password + salt);
        user.setPassword(MD5Pwd);
        user.setState(1);
        return user;
    }

    private Wxuser jsonStr2Wxuser(JSONObject jsonObject) {
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setSex(jsonObject.getInteger("sex"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));
        String country = jsonObject.getString("country");
        String province = jsonObject.getString("province");
        String city = jsonObject.getString("city");
        wxuser.setAddress(country+province+city);
        wxuser.setUnionid(jsonObject.getString("unionid"));
        return wxuser;
    }
}
